package com.airili.wiki.service.impl;

import com.airili.wiki.domain.Content;
import com.airili.wiki.domain.Doc;
import com.airili.wiki.domain.DocExample;
import com.airili.wiki.exception.BusinessException;
import com.airili.wiki.exception.BusinessExceptionCode;
import com.airili.wiki.mapper.ContentMapper;
import com.airili.wiki.mapper.DocMapper;
import com.airili.wiki.mapper.DocMapperCust;
import com.airili.wiki.req.DocQueryReq;
import com.airili.wiki.req.DocSaveReq;
import com.airili.wiki.resp.DocQueryResp;
import com.airili.wiki.resp.PageResp;
import com.airili.wiki.service.DocService;
import com.airili.wiki.service.WsService;
import com.airili.wiki.util.CopyUtil;
import com.airili.wiki.util.RedisUtil;
import com.airili.wiki.util.RequestContext;
import com.airili.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @author: Airili
 * @create: 2021-09-24 10:12
 **/
@Service
public class DocServiceImpl implements DocService {
    private static final Logger LOG = LoggerFactory.getLogger(DocServiceImpl.class);

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private DocMapper docMapper;

    @Resource
    private DocMapperCust docMapperCust;

    @Resource
    private ContentMapper contentMapper;

    @Resource
    public RedisUtil redisUtil;

    @Resource
    public WsService wsService;

    @Override
    public PageResp<DocQueryResp> list(DocQueryReq req) {
        // 以下两行代码为 Example 通用写法格式
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();

        // 根据名字模糊查询，动态SQL
//        if (!ObjectUtils.isEmpty(req.getName())) {
//            criteria.andNameLike("%" + req.getName() + "%");
//        }

        // 使用 pagehelper 分页插件，
        // 分页功能 = 查总数 (select count(0) from table) + 查当前页数据 (select xxx from table limit ?)
        // 使用时注意！！！ ： 该分页只对首个遇到的 select 起作用，所以使用的时候应该把该语句放在查询语句的前一行
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Doc> docs = docMapper.selectByExample(docExample);

        // 使用 pageinfo
        PageInfo<Doc> pageInfo = new PageInfo<>(docs);
        LOG.info("总行数: {}", pageInfo.getTotal());
        LOG.info("总页数: {}", pageInfo.getPages());

        List<DocQueryResp> docQueryResps = CopyUtil.copyList(docs, DocQueryResp.class);

        PageResp<DocQueryResp> resp = new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setList(docQueryResps);
        return resp;
    }

    @Override
    public List<DocQueryResp> all(DocQueryReq req) {
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        List<Doc> docs = docMapper.selectByExample(docExample);
        List<DocQueryResp> docQueryResps = CopyUtil.copyList(docs, DocQueryResp.class);
        return docQueryResps;
    }

    @Override
    public List<DocQueryResp> all(Long ebookId) {
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        docExample.setOrderByClause("sort asc");
        List<Doc> docList = docMapper.selectByExample(docExample);

        // 列表复制
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;
    }

    @Transactional
    @Override
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        Content content = CopyUtil.copy(req, Content.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0);
            doc.setVoteCount(0);
            docMapper.insert(doc);

            content.setId(doc.getId());
            contentMapper.insert(content);
        } else {
            // 更新
            docMapper.updateByPrimaryKey(doc);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0) {
                contentMapper.insert(content);
            }
        }
    }

    @Override
    public void delete(Long id) {
        docMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void delete(List<Long> ids) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
        docMapper.deleteByExample(docExample);
    }

    @Override
    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        // 文档阅读数+1
        docMapperCust.increaseViewCount(id);
        if (ObjectUtils.isEmpty(content)) {
            return "";
        } else {
            return content.getContent();
        }
    }

    /**
     * 点赞
     */
    @Override
    public void vote(Long id) {
        // docMapperCust.increaseVoteCount(id);
        // 远程IP+doc.id作为key，24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 5000)) {
            docMapperCust.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

        // 推送消息
        Doc docDb = docMapper.selectByPrimaryKey(id);
        String logId = MDC.get("LOG_ID");
        wsService.sendInfo("【" + docDb.getName() + "】被点赞！", logId);
        // rocketMQTemplate.convertAndSend("VOTE_TOPIC", "【" + docDb.getName() + "】被点赞！");
    }

    @Override
    public void updateEbookInfo() {
        docMapperCust.updateEbookInfo();
    }

}
